package com.example.myapplication2;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MusicActivity2 extends AppCompatActivity {
    Button button1, button2;
    MyService.MyBinder myBinder;
    boolean isBound = false;

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MyService.MyBinder) service;
            myBinder.todo();
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            myBinder = null;
            isBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music2);

        button1=findViewById(R.id.button1);
        button2=findViewById(R.id.button2);

        Intent intent = new Intent(this, MyService.class);

        button1.setOnClickListener(v -> bindService(intent, connection, Context.BIND_AUTO_CREATE));

        button2.setOnClickListener(v -> {
            if (isBound) {
                unbindService(connection);
                isBound = false;
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(connection);
            isBound = false;
        }
    }
}